﻿using Newtonsoft.Json;
using nova;
using PIMS.DBModel;
using PIMS.WorkPlugin.EAS;
using PIMS.WorkPlugin.ORM;
using PIMS.WorkPlugin.Util.Config;
using PIMS.YongXiang;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using 星瀚系统接口测试.金蝶星瀚系统.GetPackageBatchResponse;
using 星瀚系统接口测试.金蝶星瀚系统.ImportCartonInfoResponse;
using 星瀚系统接口测试.金蝶星瀚系统.QueryCartonInfoResponse;
using 金蝶星瀚系统.KingDeeRequest;
using 金蝶星瀚系统.KingDeeResponse;

namespace 金蝶星瀚系统
{
    internal class KingDee
    {
        private static string url = ConfigManager.AppSettings["easurl"].Value;//"http://yxosb.tongwei.com:8001/WP_YXESB_SOA/APP_ERP_SERVICE/BZ_PUBLIC";
        private static string urlWMS = ConfigManager.AppSettings["easurl_WMS"].Value;//"http://yxosb.tongwei.com:8001/WP_YXESB_SOA/APP_ERP_SERVICE/WMS_PUBLIC";
        private static string user = ConfigManager.AppSettings["user"].Value;//"YX35_BZHBS";
        private static string password = ConfigManager.AppSettings["password"].Value;//"29ce42d33a668d4712fc5b488ddc1304";
        private static string openApiSign = ConfigManager.AppSettings["openApiSign"].Value;//"cFhoWEpMRm03WEtvQTBPTlpybG1EY2JjMlVVemd3N1l2YTItQk0wNms4dz06MjAxMTAzNDU4MjEzMTkzNjI1Ng==";
        private static string consumer = ConfigManager.AppSettings["consumer"].Value;//"YX_BZHBS";
        public static string companyNo = ConfigManager.AppSettings["CompanyNo"].Value;//"1088"
        private static string batchHead = ConfigManager.AppSettings["batchHead"].Value;
        private static string batchNotHead = ConfigManager.AppSettings["batchNotHead"].Value;

        #region 异步调用Api
        /// <summary>
        /// https不校验ssl证书
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; // 总是接受
        }


        public static async Task<string> Task_Work_PostApi(string message)
        {
            HttpClient client = new HttpClient()
            {
                Timeout = TimeSpan.FromSeconds(10) //设置超时时间为10秒
            };

            try
            {
                /*      
                //异步调用WebApi GET请求数据
                var response = client.GetAsync(url + "/RestService/Test").Result;
                Console.WriteLine("Api请求信息：" + response.RequestMessage);
                response.EnsureSuccessStatusCode();
                if (response.IsSuccessStatusCode)
                {
                    var str = response.Content.ReadAsStringAsync().Result; //响应字符串
                    Console.WriteLine("Api输出信息：" + str);
                }
                */

                //异步调用WebApi POST请求数据
                if (!String.IsNullOrEmpty(message))
                {
                    HttpContent content = new StringContent(message, Encoding.UTF8, "application/json");
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Api请求信息：" + message);
                    var response = await client.PostAsync(url + "/RestService/" + message, content);
                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        var res = await response.Content.ReadAsStringAsync(); //响应字符串
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Api输出信息：" + res);
                        return res;
                    }
                    else
                    {
                        return response.StatusCode.ToString();
                    }
                }
                else
                {
                    return "message is null!";
                }
            }
            catch (TaskCanceledException ex)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + $"超时{client.Timeout.TotalSeconds}秒: {ex.Message}");
                return $"访问接口{url}出错，超时{client.Timeout.TotalSeconds}秒,请重试！";
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + ex.Message);
                NetLog.CreateLog(ex);
                return ex.Message;
            }           
        }
		#endregion

		/// <summary>
		/// 后台发送POST请求（同步）
		/// <summary>
		/// <param name="url">服务器地址</param>
		/// <param name="data">发送的数据</param>
		/// <returns></returns>
		private static string HttpPost(string url, string data, Dictionary<string, string> header)
		{
			if (url.ToLower().StartsWith("https"))
			{
				//NET4使用
				ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
					 | SecurityProtocolType.Tls
					 | (SecurityProtocolType)0x300 //Tls11
					 | (SecurityProtocolType)0xC00; //Tls12
													//不校验SSL
				ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
			}

			//创建post请求
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			request.Proxy = null;
			request.Method = "POST";
			foreach (string key in header.Keys)
			{
				request.Headers.Add(key, header[key]);
			}
			request.ContentType = "application/json;charset=UTF-8";
			byte[] payload = Encoding.UTF8.GetBytes(data);
			request.ContentLength = payload.Length;

			//发送post的请求
			Stream writer = request.GetRequestStream();
			writer.Write(payload, 0, payload.Length);
			writer.Close();

            //接受返回来的数据
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string value = reader.ReadToEnd();

            reader.Close();
            stream.Close();
            response.Close();

            return value;
		}

		private static long GetTimeStamp()
		{
			TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
			return Convert.ToInt64(ts.TotalMilliseconds);
		}

		/// <summary>
		/// 生产批号查询接口
		/// </summary>
		/// <param name="company"></param>
		/// <returns></returns>
		public static string GetManufacturebatch(string company = "")
        {
            try
			{
				var temporary = new
				{
					company = company, //公司
					queryDays = 60, //查询天数
					bizType = "",   //业务类型
					outDate = "",   //出炉日期
					heatNo = "",     //炉号
					outPackNum = "" //出包数
				};

				//OSB
				Dictionary<string, string> header = new Dictionary<string, string>();
				header.Add("openApiSign", openApiSign);

				RequestRoot reqRoot = new RequestRoot(temporary);
				reqRoot.Request.Head.ACCOUNT = user;
				reqRoot.Request.Head.PASSWORD = password;
				reqRoot.Request.Head.SRVLEVEL = "1";
				reqRoot.Request.Head.BIZTRANSACTIONID = "HBS_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
				reqRoot.Request.Head.CONSUMER = consumer;
				reqRoot.Request.Head.COMPANY = companyNo;
				reqRoot.Request.Head.TIMESTAMP = GetTimeStamp().ToString();

				var req = JsonConvert.SerializeObject(reqRoot);
				//NetLog.CreateLog($"GetManufacturebatch() 发送报文:{req}");
				var res = HttpPost(url + "/pom_queryProductLotData", req, header);
				//NetLog.CreateLog($"GetManufacturebatch() 响应报文:{res}");

				ResponseRoot<ProductLot> responseRoot = JsonConvert.DeserializeObject<ResponseRoot<ProductLot>>(res);

				if (responseRoot.Response.Data.status)
				{
                    //return responseRoot.Response.Data.data;
                    foreach (var item in responseRoot.Response.Data.data)
                    {
                        //if ( /*1 == item.CFBATCHTYPE ||*/ item.FNUMBER.StartsWith("YT-A") || item.FNUMBER.StartsWith("YN-B") || item.FNUMBER.StartsWith("YN-C")
                        //    || item.FNUMBER.StartsWith("YN-D") || item.FNUMBER.StartsWith("YNH"))
                        if (FilterBatchNo(item.number, batchHead) && (String.IsNullOrEmpty(batchNotHead) ||
                            (!String.IsNullOrEmpty(batchNotHead) && !FilterBatchNo(item.number, batchNotHead))))
                        {
                            int nRet = 0;
                            //string strRet = string.Format("if  not exists (select * from EASBatch  where Batch='{0}') Insert Into EASBatch (Batch,[type],CreateAt) Values('{1}',{2},'{3}')",
                            //                        item.FNUMBER,
                            //                        item.FNUMBER,
                            //                        item.CFBATCHTYPE,
                            //                        item.FCREATETIME);
                            //int nRet = DbHelperSQL.ExecuteSql(strRet);
                            EASBatch easBatch = SqlSugarHelper.Query<EASBatch>(
                                String.Format("Batch='{0}'", item.number), "CreateAt");
                            if (easBatch == null)
                            {
                                easBatch = new EASBatch();
                                easBatch.Batch = item.number;
                                easBatch.type = item.batchType;
                                easBatch.CreateAt = item.bantchDate.ToString();
                                nRet = SqlSugarHelper.InsertRecord<EASBatch>(easBatch);
                            }
                        }
                    }
					return "查询成功";
                }
				//throw new Exception(responseRoot.Response.Data.errorMessage.errorMessage);
				return "Err:" + responseRoot.Response.Data.errorMessage.errorMessage;

            }
			catch (Exception ex)
			{
				NetLog.CreateLog(ex);
				return "Err:" + ex.Message;
			}
		}

		/// <summary>
		/// 包装批号查询接口
		/// </summary>
		/// <param name="probatchno"></param>
		/// <returns></returns>
		public static List<PackageBatch> GetPackageBatch(string probatchno)
        {
			try
			{
				var temporary = new
				{
					proBatchNo = probatchno //0606
				};

				//OSB
				Dictionary<string, string> header = new Dictionary<string, string>();
				header.Add("openApiSign", openApiSign);

				RequestRoot reqRoot = new RequestRoot(temporary);
				reqRoot.Request.Head.ACCOUNT = user;
				reqRoot.Request.Head.PASSWORD = password;
				reqRoot.Request.Head.SRVLEVEL = "1";
				reqRoot.Request.Head.BIZTRANSACTIONID = "HBS_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
				reqRoot.Request.Head.CONSUMER = consumer;
				reqRoot.Request.Head.COMPANY = companyNo;
				reqRoot.Request.Head.TIMESTAMP = GetTimeStamp().ToString();

				var req = JsonConvert.SerializeObject(reqRoot);
				//NetLog.CreateLog($"GetPackageBatch() 发送报文:{req}");
				var res = HttpPost(url + "/kdcd_mmcbasedata_queryPackageBatch", req, header);
				//NetLog.CreateLog($"GetPackageBatch() 响应报文:{res}");

				GetPackageBatchResponse responseRoot = JsonConvert.DeserializeObject<GetPackageBatchResponse>(res);
				if (responseRoot.Response.Data.status)
				{
					return responseRoot.Response.Data.data;
				}
				throw new Exception(responseRoot.Response.Data.message);
			}
			catch (Exception ex)
			{
				NetLog.CreateLog(ex);
				throw ex;
			}
		}
        /// <summary>
        /// 箱号上传接口
        /// </summary>
        /// <param name="boxId"></param>
        /// <returns></returns>
        public static string Import_CartonInfo(string boxId)
        {
            string packtype = "";
            //OSB
            Dictionary<string, string> header = new Dictionary<string, string>();
            //header.Add("Accept-Encoding", ""); //不支持压缩
            header.Add("openApiSign", openApiSign);

            金蝶星瀚系统.KingDeeRequest.CartonInfo cartonInfo = new 金蝶星瀚系统.KingDeeRequest.CartonInfo();
            cartonInfo.number = boxId; //包装箱号
            cartonInfo.billStatus = "A"; //新增
            cartonInfo.businesstype = "A"; //2024.0809 业务类型，默认为A
            cartonInfo.companyNo = companyNo; //公司编码
            cartonInfo.bizDate = DateTime.Now.ToString("yyyy-MM-dd");

            try
            {
                DataTable dtBox = SqlSugarHelper.QueryToDataTable<saveddata>(
                    string.Format("select * from tb_saveddata where uid='{0}'", boxId));
                DataTable dtBag = SqlSugarHelper.QueryToDataTable<saveddataBag>(
                    string.Format("select * from tb_saveddataBag where boxid='{0}'", boxId));

                if (0 < dtBox.Rows.Count)
                {
                    if (dtBox.Rows[0]["reserved7"].ToString().Trim() == "1") //上传EAS标志
                    {
                        return "Err:" + "重复上传!" + boxId;
                    }

                    cartonInfo.carNo = dtBox.Rows[0]["reserved6"].ToString().Trim(); //车号
                    cartonInfo.productLine = "";

                    if (string.IsNullOrEmpty(dtBox.Rows[0]["reserved2"].ToString().Trim())) //定制料信息
                        cartonInfo.cusMateInfo = dtBox.Rows[0]["reserved3"].ToString().Trim(); //客户单位
                    else
                        cartonInfo.cusMateInfo = dtBox.Rows[0]["reserved2"].ToString().Trim() + ";" //定制料信息
                                + dtBox.Rows[0]["reserved3"].ToString().Trim(); //客户单位
                    cartonInfo.partSize = dtBox.Rows[0]["productMark"].ToString().Trim(); //粒径
                    cartonInfo.gweight = dtBox.Rows[0]["reserved1"].ToString().Trim();
                    cartonInfo.nweight = dtBox.Rows[0]["weight"].ToString().Trim();
                    //cartonInfo.material = dtBox.Rows[0]["reserved11"].ToString().Trim(); //物料编码
                    cartonInfo.proLotNo = dtBox.Rows[0]["batchNo"].ToString().Trim(); //生产批号
                    cartonInfo.packagelotNo = dtBox.Rows[0]["reserved5"].ToString().Trim(); //包装批号

                    cartonInfo.materialConditionName = dtBox.Rows[0]["productName"].ToString().Trim(); //料况编码

                    List<MaterialCondition> list = KingDee.MaterialConditionQuery();
                    foreach (MaterialCondition item in list)
                    {
                        if (cartonInfo.materialConditionName == item.name)
                        {
                            cartonInfo.materialCondition = item.number;
                            break;
                        }
                    }
                    if (String.IsNullOrEmpty(cartonInfo.materialCondition))
                    {
                        return $"Err:料况<{cartonInfo.materialConditionName}>对应的料况编码不存在！请确认料况是否正确。";
                    }
                    string[] strings = cartonInfo.packagelotNo.Split('/');
                    if (5 == strings.Length)
                    {
                        packtype = strings[3] + "/" + strings[4];
                    }
                    
                    RequestRoot reqRoot = new RequestRoot(cartonInfo);
                    reqRoot.Request.Head.USE = "箱号信息上传接口";
                    reqRoot.Request.Head.ACCOUNT = user;
                    reqRoot.Request.Head.PASSWORD = password;
                    reqRoot.Request.Head.SRVLEVEL = "1";
                    reqRoot.Request.Head.COUNT = "1";
                    reqRoot.Request.Head.BIZTRANSACTIONID = "HBS_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    reqRoot.Request.Head.CONSUMER = consumer;
                    reqRoot.Request.Head.COMPANY = companyNo;
                    reqRoot.Request.Head.TIMESTAMP = GetTimeStamp().ToString();
                    var req = JsonConvert.SerializeObject(reqRoot);
                    //NetLog.CreateLog($"Import_CartonInfo() 发送报文:{req}");
                    var res = HttpPost(url + "/kdcd_mmcbasedata_cargoDataApi", req, header);
                    //NetLog.CreateLog($"Import_CartonInfo() 响应报文:{res}");

                    ImportCartonInfoResponseRoot responseRoot = JsonConvert.DeserializeObject<ImportCartonInfoResponseRoot>(res);
                    if (responseRoot.Response.Data.status)
                    {
                        SqlSugarHelper.UpdateRecord<saveddata>(String.Format("uid='{0}'", boxId),
                          new Dictionary<string, object>() { { "reserved7", "1" }, { "reserved10", packtype } }); //上传EAS标志
                        return "";
                    }
                    else
                    {
                        return "Err:" + responseRoot.Response.Head.ERRORINFO;
                    }
                }
                else
                {
                    return "Err:" + "数据库中没有此箱标的记录!" + boxId;
                }
                //if (dtBag.Rows.Count > 0)
                //{
                //    for (int i = 0; i < dtBag.Rows.Count; i++)
                //    {
                //        cartonInfo.detail.Add(dtBag.Rows[i]["uid"].ToString().Trim()); //袋标
                //    }
                //}
                //else
                //{
                //    return "Err:" + "数据库中此箱标绑定的袋标记录!" + boxId;
                //}
            }
            catch(Exception e)
            {
                if (e.Message.Contains("已存在!不能重复导入"))
                {
                    SqlSugarHelper.UpdateRecord<saveddata>(String.Format("uid='{0}'", boxId),
                      new Dictionary<string, object>() { { "reserved7", "1" }, { "reserved10", packtype } }); //上传EAS标志
                }
                return "Err:" + e.Message;
            }
        }

        /// <summary>
        /// 2.28.	托码回传接口（Import_CpRelation）
        /// </summary>
        public static string Import_CpRelation(string[] cartonNumbers, string palletNumber)
        {
            try
            {
                //OSB
                Dictionary<string, string> header = new Dictionary<string, string>();
                //header.Add("Accept-Encoding", ""); //不支持压缩
                header.Add("openApiSign", openApiSign);
                PalletInfo pInfo = new PalletInfo();
                pInfo.entries = new Entry[cartonNumbers.Length];
                for (int i = 0; i < cartonNumbers.Length; i++)
                {
                    pInfo.entries[i] = new Entry(cartonNumbers[i]);
                }
                pInfo.pallet = palletNumber;

                RequestRoot reqRoot = new RequestRoot(pInfo);
                reqRoot.Request.Head.USE = "组托信息上传接口";
                reqRoot.Request.Head.ACCOUNT = user;
                reqRoot.Request.Head.PASSWORD = password;
                reqRoot.Request.Head.SRVLEVEL = "1";
                reqRoot.Request.Head.COUNT = "1";
                reqRoot.Request.Head.BIZTRANSACTIONID = "HBS_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                reqRoot.Request.Head.CONSUMER = consumer;
                reqRoot.Request.Head.COMPANY = companyNo;
                reqRoot.Request.Head.TIMESTAMP = GetTimeStamp().ToString();
                var req = JsonConvert.SerializeObject(reqRoot);
                //NetLog.CreateLog($"Import_CartonInfo() 发送报文:{req}");
                var res = HttpPost(urlWMS + "/kdcd_mmcbasedata_teamCarrier", req, header);
                //NetLog.CreateLog($"Import_CartonInfo() 响应报文:{res}");

                ImportPalletnInfoResponseRoot responseRoot = JsonConvert.DeserializeObject<ImportPalletnInfoResponseRoot>(res);
                if (responseRoot.Response.Data.status)
                {
                    SqlSugarHelper.UpdateRecord<saveddata>(String.Format("uid='{0}' or uid='{1}'", cartonNumbers[0], cartonNumbers[1]),
                       new Dictionary<string, object>() { { "reserved15", "1" }, { "reserved20", palletNumber } }); //上传EAS标志
                }
                else
                {
                    //return "Err:" + responseRoot.Response.Data.errorMessage;
                    return "Err:" + responseRoot.Response.Head.ERRORINFO;
                }
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    Stream stream = we.Response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    MessageBox.Show(value, "Ex");
                }
            }
            catch (Exception ex)
            {
                return ex.Message + ex.StackTrace;
            }
            return "";
        }

        /// <summary>
        /// 箱号作废
        /// </summary>
        /// <param name="cartonNumber"></param>
        /// <param name="reason"></param>
        /// <returns></returns>
        public static 金蝶星瀚系统.KingDeeResponse.Result Import_UnqualifiedCarton(string boxId, string oper = "", string reason = "")
        {
            //OSB
            Dictionary<string, string> header = new Dictionary<string, string>();
            //header.Add("Accept-Encoding", ""); //不支持压缩
            header.Add("openApiSign", openApiSign);

            金蝶星瀚系统.KingDeeRequest.CartonInfo cartonInfo = new 金蝶星瀚系统.KingDeeRequest.CartonInfo();
            cartonInfo.number = boxId;
            cartonInfo.billStatus = "R"; //作废
            cartonInfo.enableFlage = "10";
            cartonInfo.disableUser = oper;
            //cartonInfo.sourceSystem = "HBS"; //

            RequestRoot reqRoot = new RequestRoot(cartonInfo);
            reqRoot.Request.Head.ACCOUNT = user;
            reqRoot.Request.Head.PASSWORD = password;
            reqRoot.Request.Head.SRVLEVEL = "1";
            reqRoot.Request.Head.BIZTRANSACTIONID = "HBS_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            reqRoot.Request.Head.CONSUMER = consumer;
            reqRoot.Request.Head.COMPANY = companyNo;
            reqRoot.Request.Head.TIMESTAMP = GetTimeStamp().ToString();
            var req = JsonConvert.SerializeObject(reqRoot);
            NetLog.CreateLog($"Import_UnqualifiedCarton() 发送报文:{req}");
            var res = HttpPost(url + "/kdcd_mmcbasedata_cargoDataApi", req, header);
            NetLog.CreateLog($"Import_UnqualifiedCarton() 响应报文:{res}");

            金蝶星瀚系统.KingDeeResponse.Result result = new 金蝶星瀚系统.KingDeeResponse.Result();
            ImportCartonInfoResponseRoot responseRoot = JsonConvert.DeserializeObject<ImportCartonInfoResponseRoot>(res);            
            if (responseRoot.Response.Data.status)
            {
                result.msg = responseRoot.Response.Data.data.info;
                result.flag = 1;
            }
            else
            {
                result.msg = responseRoot.Response.Head.ERRORINFO;
                result.flag = 0;
            }
            return result;
        }

		/// <summary>
		/// 料况查询接口
		/// </summary>
		/// <returns></returns>
		public static List<MaterialCondition> MaterialConditionQuery()
        {
			try
			{
				//OSB
				Dictionary<string, string> header = new Dictionary<string, string>();
				header.Add("openApiSign", openApiSign);

				RequestRoot reqRoot = new RequestRoot("{}");
				reqRoot.Request.Head.ACCOUNT = user;
				reqRoot.Request.Head.PASSWORD = password;
				reqRoot.Request.Head.SRVLEVEL = "1";
				reqRoot.Request.Head.BIZTRANSACTIONID = "HBS_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
				reqRoot.Request.Head.CONSUMER = consumer;
				reqRoot.Request.Head.COMPANY = companyNo;
				reqRoot.Request.Head.TIMESTAMP = GetTimeStamp().ToString();

				var req = JsonConvert.SerializeObject(reqRoot);
				NetLog.CreateLog($"MaterialConditionQuery() 发送报文:{req}");
				//var res = await PostApi(url + "/pom_queryMaterialCondition", req, header, 60);
                var res = HttpPost(url + "/pom_queryMaterialCondition", req, header);
				NetLog.CreateLog($"MaterialConditionQuery() 响应报文:{res}");

				ResponseRoot<MaterialCondition> responseRoot = JsonConvert.DeserializeObject<ResponseRoot<MaterialCondition>>(res);
				if (responseRoot.Response.Data.status)
				{
					return responseRoot.Response.Data.data;
				}
				throw new Exception(responseRoot.Response.Data.errorMessage.errorMessage);
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}

		/// <summary>
		/// 查询箱号信息
		/// </summary>
		/// <param name="boxId"></param>
		/// <returns></returns>
		public static string QueryCartonInfo(string param, string value, out BoxHistory carton)
        {
            carton = new BoxHistory();

            try
            {
                //OSB
                Dictionary<string, string> header = new Dictionary<string, string>();
                header.Add("openApiSign", openApiSign);
                bool bBox = false;
                QueryCargo queryCargo = new QueryCargo();
                if (param.StartsWith("pallet"))
                    queryCargo.pallet = value;
                else
                {
                    queryCargo.cartNo = value;
                    bBox = true;
                }

                RequestRoot reqRoot = new RequestRoot(queryCargo);
                reqRoot.Request.Head.ACCOUNT = user;
                reqRoot.Request.Head.PASSWORD = password;
                reqRoot.Request.Head.SRVLEVEL = "1";
                reqRoot.Request.Head.BIZTRANSACTIONID = "HBS_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                reqRoot.Request.Head.CONSUMER = consumer;
                reqRoot.Request.Head.COMPANY = companyNo;
                reqRoot.Request.Head.TIMESTAMP = GetTimeStamp().ToString();

                var req = JsonConvert.SerializeObject(reqRoot);
                //NetLog.CreateLog($"QueryCartonInfo() 发送报文:{req}");
                var res = HttpPost(urlWMS + "/kdcd_mmcbasedata_queryCargo", req, header);
                //NetLog.CreateLog($"QueryCartonInfo() 响应报文:{res}");

                QueryCartonInfoResponse responseRoot = JsonConvert.DeserializeObject<QueryCartonInfoResponse>(res);
                if (responseRoot.Response.Data.status)
                {
                    //return responseRoot.Response.Data.data.ToString();
                    carton = JsonConvert.DeserializeObject<BoxHistory[]>(responseRoot.Response.Data.data.ToString())[0];
                    if (bBox)
                    {
                        DataTable dtBox = SqlSugarHelper.QueryToDataTable<saveddata>(
                                string.Format("select * from tb_saveddata where uid='{0}'", carton.cartNo));

                        if (dtBox.Rows.Count == 0)
                        {
                            saveddata boxManual = new saveddata();
                            boxManual.uid = carton.cartNo;
                            boxManual.packager = "0";
                            boxManual.workOrder = DateTime.Now.ToString("yyMMddHHmmss");
                            boxManual.batchNo = carton.productLotNumber;
                            boxManual.productName = carton.materialCondition;
                            boxManual.productMark = carton.partSize;
                            boxManual.weight = carton.nWeight.ToString();
                            boxManual.reserved1 = carton.gWeight.ToString();
                            if (null != carton.cusMaterialInfo)
                                boxManual.reserved3 = carton.cusMaterialInfo.ToString();
                            boxManual.reserved5 = carton.packageLotNo;
                            boxManual.reserved8 = carton.billstatus;
                            boxManual.reserved10 = carton.packageRule;
                            boxManual.reserved11 = carton.materialNo;
                            boxManual.reserved20 = carton.pallet;
                            if (!string.IsNullOrEmpty(carton.packageTime))
                            {
                                boxManual.productTime = Convert.ToDateTime(carton.packageTime);
                            }
                            else
                                boxManual.productTime = DateTime.Now;
                            if (0 >= SqlSugarHelper.InsertRecord(boxManual))
                                return "Err:人工箱插入数据库失败!!!";
                        }
                        else if (carton.cartNo.Trim().Length == 15)
                        {
                            SqlSugarHelper.UpdateRecord<saveddata>(string.Format("uid='{0}'", carton.cartNo),
                                    new Dictionary<string, object>() { { "reserved10", carton.packageRule } });
                        }
                    }
                    return "";
                }
                return "Err:" + responseRoot.Response.Data.errorMessage.errorMessage;
            }
            catch (Exception ex)
            {
                //NetLog.CreateLog(ex);
                return "Err:" + ex.Message;
            }
        }

        private static bool FilterBatchNo(string batchNo, string filterStr)
        {
            if (String.IsNullOrEmpty(filterStr))
            {
                return true;
            }
            else
            {
                if (filterStr.Contains("|"))
                {
                    string[] strs = filterStr.Split('|');
                    foreach (string s in strs)
                    {
                        if (batchNo.Contains(s))
                        {
                            return true;
                        }
                    }

                }
                else
                {
                    if (batchNo.Contains(filterStr))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

    }

}
